import React, { useState, useEffect } from 'react';
import { Table, Tag, Spin, Alert } from 'antd';
import axios from 'axios';

const HotPlaylistRanking = () => {
  // 表格列定义
  const columns = [
    {
      title: '排名',
      dataIndex: 'ranking',
      key: 'ranking',
      width: 80,
      render: rank => (
        <Tag color={rank <= 3 ? '#f50' : '#108ee9'}>
          {rank}
        </Tag>
      )
    },
    {
      title: '歌单名称',
      dataIndex: 'name',
      key: 'title',
      render: (text, record) => (
        <div>
          <span style={{ marginRight: 8 }}>{text}</span>
          <Tag color="#2db7f5">热度值: {record.hot_score?.toFixed(1)}</Tag>
        </div>
      )
    },
    {
      title: '播放量',
      dataIndex: 'play_count',
      key: 'play_count',
      render: count => count?.toLocaleString() || 0
    },
    {
      title: '收藏量',
      dataIndex: 'favorite_count',
      key: 'favorite_count',
      render: count => {
        // 处理字符串类型的收藏量
        const num = parseInt(count || 0);
        return isNaN(num) ? '无效值' : num.toLocaleString();
      }
    },
    {
      title: '分享量',
      dataIndex: 'share_count',
      key: 'share_count',
      render: count => count?.toLocaleString() || 0
    },
    {
      title: '评论量',
      dataIndex: 'comment_count',
      key: 'comment_count',
      render: count => count?.toLocaleString() || 0
    }
  ];

  // 状态管理
  const [rankingData, setRankingData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 数据获取
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('http://localhost:5000/playlists/hot');

        if (response.data.success) {
          // 数据预处理（兼容后端原始格式）
          const processedData = response.data.data.map(item => ({
            ...item,
            play_count: Number(item.play_count) || 0,
            favorite_count: item.favorite_count?.toString() || '0', // 保留字符串类型
            share_count: Number(item.share_count) || 0,
            comment_count: Number(item.comment_count) || 0,
            hot_score: Number(item.hot_score) || 0
          }));

          setRankingData(processedData);
          setError(null);
        } else {
          setError(response.data.error || '服务器返回未知错误');
        }
      } catch (error) {
        setError(error.response?.data?.error || '无法连接服务器');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
    const interval = setInterval(fetchData, 300000); // 5分钟刷新
    return () => clearInterval(interval);
  }, []);

  // 渲染逻辑
  return (
    <div style={{ padding: 24 }}>
      {error ? (
        <Alert
          message="数据加载失败"
          description={`错误原因: ${error}`}
          type="error"
          showIcon
        />
      ) : (
        <Table
          columns={columns}
          dataSource={rankingData}
          loading={loading}
          pagination={{ pageSize: 20 }}
          rowKey="id"
          bordered
          title={() => (
            <h2 style={{ margin: 0 }}>
              🎵 热门歌单排行榜
            </h2>
          )}
        />
      )}
    </div>
  );
};

export default HotPlaylistRanking;